/**
 * 公共组件
 * @author xiaoxujs
 */

import { Content, Header } from "antd/es/layout/layout";
import { ButtonBaise, HomeBox, TabsBox, TabsBoxErji, TabsBoxYiji } from "./style";
import { ConfigProvider, Dropdown, message, Space, Tooltip } from "antd";
import { useCallback, useEffect, useState } from "react";
// import { IMenyItem } from "../../type/antd";
import { IBaseNameGet, ILoginDataTree, ISessionUserData } from "../../type/login";
import { Outlet, useNavigate } from "react-router-dom";
import { DownOutlined } from "@ant-design/icons";
import { ItemType, SubMenuType } from "antd/es/menu/interface";
import useWindowSize from "../../assets/fun/commit/useWindowSize";
import { useWindowFontSize } from "../../assets/fun/Antd/configprovider";
import LogoName from './components/LogoName';
import { getBaseNameGet } from "../../api/login";
// import { basicIp } from "../../api/http";

interface IMenyItem {
    icon?: string; //图标
    key: string
    label: string;
    selected?: boolean;
    children: IMenyItem[];
}

const Home = () => {
    const navigate = useNavigate();
    const { height } = useWindowSize()

    const [enumData, setEnumData] = useState<IMenyItem[]>([]); //菜单数据
    const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
    const [personData, setpersonData] = useState<ISessionUserData>();
    const [logoNameShow, setLogoNameShow] = useState(false);
    const [logoNameValue, setLogoNameValue] = useState<IBaseNameGet>();
    const [yiList, setYiList] = useState<IMenyItem[]>([]); // 菜单一
    const [erList, setErList] = useState<IMenyItem[]>([]); // 菜单一
    // 监听菜单数据
    const jiantongFun = useCallback(
        () => {
            const arr = [...enumData];
            setYiList(arr);
            arr.forEach(element => {
                if (element.key === selectedKeys[0]) {
                    setErList(element.children)
                }
            });
        },
        [enumData, selectedKeys],
    );
    useEffect(() => {
        jiantongFun();
    }, [jiantongFun])



    // 获取系统信息
    const handleLogoName = useCallback(
        async () => {
            const { code, msg, data } = await getBaseNameGet() as { code: number; msg: string, data: IBaseNameGet };
            if (code === 20000) {
                setLogoNameValue(data)
            } else {
                message.error(msg)
            }
        },
        [],
    )

    /**
     * 整理权限函数
     * @param dataArr 所有权限
     * @param buttonData 按钮权限 
     * @param menuData 菜单权限
     */
    const menuquanxainFun = useCallback(
        (dataArr: ILoginDataTree[], buttonData: string[], menuData?: ItemType[]) => {
            dataArr.forEach((element, index) => {
                if (element.menuType === 'C') {
                    let data = {
                        label: element.menuName,
                        key: element.url,
                        icon: element.icon === '#' ? '' : <span className="anticon anticon-appstore">
                            <span className="iconfont" style={{ fontSize: '2.4rem' }} dangerouslySetInnerHTML={{ __html: element.icon }} ></span>
                        </span>,
                    }
                    if (element.children && element.children.length > 0 && element.children[0].menuType === 'C') {
                        if (menuData) {
                            let newData: SubMenuType = {
                                ...data,
                                children: []
                            }
                            menuData.push(newData)
                            if (menuData.length > 0) {
                                menuquanxainFun(element.children, buttonData, newData.children);
                            } else {
                                menuquanxainFun(element.children, buttonData);
                            }

                        }
                    } else {
                        menuData && menuData.push({
                            ...data
                        })
                    }
                } else if (element.menuType === 'F') { //  f是按钮
                    buttonData.push(element.perms);
                }
            })
        },
        []
    );
    useEffect(() => {
        let data = sessionStorage.getItem('tabsTree');
        let userData = sessionStorage.getItem('userInfo');
        if (userData) {
            setpersonData(JSON.parse(userData) as ISessionUserData)
        }
        if (data) {
            let sessionData = JSON.parse(data) as ILoginDataTree[]
            let menuSessionList: IMenyItem[] = []
            let buttonSessionList: string[] = []
            menuquanxainFun(sessionData, buttonSessionList, menuSessionList);
            console.log(menuSessionList)
            setEnumData([...menuSessionList])
        }
    }, [menuquanxainFun])
    // 获取打开的路径
    useEffect(() => {
        handleLogoName();
        const sessionData = sessionStorage.getItem("keyPath");
        if (sessionData) {
            setSelectedKeys(JSON.parse(sessionData) as string[]);
        }
        return () => { }
    }, [handleLogoName])

    //点击一级
    const handleClickMenu  = (key: string) => {
        setSelectedKeys([key, key]);
        sessionStorage.setItem("keyPath", JSON.stringify([key, key]));
        navigate(key);
    };
    const handleLoginOut = () => {
        // 退出登录
        navigate("/");
        sessionStorage.removeItem("token");
        sessionStorage.removeItem("userInfo");
    };
    // 修改系统信息弹窗 回调
    const handleCallback = () => {
        setLogoNameShow(false);
        handleLogoName();
    }
    // 点击二级菜单
    const handleErClick = (key: string) => {
        sessionStorage.setItem("keyPath", JSON.stringify([selectedKeys[0], key]));
        setSelectedKeys([selectedKeys[0], key]);
        navigate(key);
    }

    const items = [
        {
            key: "2",
            label: <span onClick={() => handleLoginOut()}>退出登录</span>,
        },
    ];
    return <HomeBox>
        <Header className="header-box">
            <ConfigProvider
                theme={{
                    components: {
                        Menu: {
                            itemColor: '#FFFFFF',
                            horizontalItemSelectedColor: '#FFFFFF',
                            itemHoverColor: '#FFFFFF',
                        }
                    }
                }}
            >
                <div className="demo-logo" >
                    <div className="demo-logo-image"></div>
                    <div className="demo-logo-text">发运系统</div>
                </div>
                {/* <div className="menu-wai-box">
                    <Menu style={{ width: useWindowFontSize((enumData.length + 1) * 93) + 'rem' }} className="menu-box" onClick={handleClickMenu} selectedKeys={selectedKeys} mode="horizontal" items={enumData} />
                </div> */}
                <div className="name_box">
                    {/* <Tooltip title="修改系统名">
                        <span className="iconfont" style={{ cursor: 'pointer' }} onClick={() => setLogoNameShow(true)}>&#xe642;</span>
                    </Tooltip> */}
                    <Dropdown menu={{ items }}>
                        <ButtonBaise>
                            <Space>
                                {personData && personData.userName}
                                <DownOutlined />
                            </Space>
                        </ButtonBaise>
                    </Dropdown>
                </div>

            </ConfigProvider>
        </Header>
        <Content className="content-box" style={{ height: height - useWindowFontSize(60) }} >
            <TabsBox>
                <TabsBoxYiji>
                    {
                        yiList.map(item => <li key={item.key} onClick={() => handleClickMenu(item.key)} className={item.key === selectedKeys[0] ? 'xuanzhong' : ''}>
                            <div className="iconfont_box"><span className="iconfont">{item.icon}</span></div>
                            <div>{item.label}</div>
                            {
                                item.key === selectedKeys[0] && <div className="gun"></div>
                            }
                        </li>)
                    }

                </TabsBoxYiji>
                <TabsBoxErji>
                    {
                        erList.map(item => <li onClick={() => handleErClick(item.key)} key={item.key} className={item.key === selectedKeys[1] ? 'xuanzhong' : ''}>
                            {/* <div className="iconfont_box"><span className="iconfont">{item.icon}</span></div> */}
                            {item.label}
                        </li>)
                    }
                </TabsBoxErji>
            </TabsBox>
            <Outlet />
        </Content>
        <LogoName open={logoNameShow} handleCallback={handleCallback} logoNameValue={logoNameValue} />
    </HomeBox>
}

export default Home;